package com.woniuxy.boot.nb_upload.controller;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;

//上传图片 上传图片

@RestController
public class UploadController {

    @Value("${sftp.host}")
    private String host;

    @Value("${sftp.user}")
    private String user;

    @Value("${sftp.password}")
    private String password;

    @Value("${sftp.remote-directory}")
    private String remoteDirectory;

    @Value("${sftp.server-url}")
    private String serverUrl;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        System.out.println("=============================>>>>>>>>>>>>>>>>>"+file);
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a file to upload.");
        }
        try {
            // 创建临时文件
            File tempFile = File.createTempFile("temp", "." + getFileExtension(file.getOriginalFilename()));
            file.transferTo(tempFile);

            // 上传文件
            String imageUrl = uploadFileToServer(tempFile, file.getOriginalFilename());

            // 删除临时文件
            tempFile.delete();

            return ResponseEntity.ok(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Failed to upload image: " + e.getMessage());
        }
    }

    private String uploadFileToServer(File localFile, String fileName) throws Exception {
        // 创建JSch对象
        JSch jsch = new JSch();
        // 创建会话
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        // 设置第一次连接时不进行主机密钥检查
        session.setConfig("StrictHostKeyChecking", "no");
        // 连接
        session.connect();

        // 创建SFTP通道
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();

        // 上传文件
        FileInputStream fis = new FileInputStream(localFile);
        sftpChannel.cd(remoteDirectory);
        sftpChannel.put(fis, fileName);

        // 构建图片链接
        String imageUrl = "http://"+serverUrl  +  "/" +fileName;

        // 关闭资源
        fis.close();
        sftpChannel.disconnect();
        session.disconnect();
        System.out.println(imageUrl);
        return imageUrl;
    }

    private String getFileExtension(String filename) {
        int lastIndexOf = filename.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ""; // empty extension
        }
        System.out.println(filename.substring(lastIndexOf + 1).toString());
        return filename.substring(lastIndexOf + 1).toString();
    }
}